package com.ocm.commerceinteraction;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;

import com.easemob.EMConnectionListener;
import com.easemob.EMError;
import com.easemob.chat.CmdMessageBody;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.EMNotifier;
import com.easemob.chat.GroupChangeListener;
import com.easemob.chat.TextMessageBody;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ocm.commerceinteraction.config.RequestAddr;
import com.ocm.commerceinteraction.model.BaseModel;
import com.ocm.commerceinteraction.model.CenterMessage;
import com.ocm.commerceinteraction.model.FriendsList;
import com.ocm.commerceinteraction.model.GroupDetail;
import com.ocm.commerceinteraction.model.LoginModel;
import com.ocm.commerceinteraction.model.UserInfo;
import com.ocm.commerceinteraction.model.UserModel;
import com.ocm.commerceinteraction.ui.adapter.XTContactAdapter;
import com.ocm.commerceinteraction.util.XTHttp;
import com.ocm.commerceinteraction.util.helper.DBHelper;
import com.ocm.commerceinteraction.util.helper.LogHelper;
import com.ocm.commerceinteraction.util.helper.NotifyUtil;
import com.ocm.commerceinteraction.util.http.AjaxCallBack;

import org.apache.http.client.CookieStore;
import org.litepal.LitePalApplication;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import easeui.controller.EaseUI;
import easeui.domain.EaseUser;

//import com.hyphenate.chat.EMClient;
//import com.hyphenate.chat.EMOptions;
import com.easemob.luckymoneysdk.core.LMMoney;
/**
 * Created by Curry on 2016-4-14.
 */
public class GlobalApplication extends LitePalApplication {

    public static Context applicationContext;
    public static Context context;
    public static GlobalApplication globalApplication;
    public static LoginModel loginModel;

    public static CookieStore localCookie;

    public static EaseUI easeUI;

    public static Gson gson;//gson json转换工具

    public static XTHttp xtHttp;//http访问

    public static boolean chat_to_home=false;//刷新群列表
    public static boolean chat_msg_clear=false;//刷新消息列表

    public static GlobalApplication getInstance() {
        return globalApplication;
    }

    public static List<UserInfo> userInfoList = new ArrayList<>();

    public static Map<String, Integer> unReadListFri = new HashMap<>();//好友未读列表

    public static Map<String, Integer> unReadListGroup = new HashMap<>();//群组未读列表


    public static boolean newMsgFlag = false;

    public static GroupDetail userGroupDetail;

    public static List<String> groupBlockList = new ArrayList<>();//全体禁言列表
    public static Map<String, String> privateBlockList = new HashMap<>();//群个人禁言列表

    public  static  NewMessageBroadcastReceiver msgReceiver ;
    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        globalApplication = this;
        gson = new Gson();
        xtHttp = new XTHttp();
        easeUI.getInstance().init(getApplicationContext());
        userInfoList = new ArrayList<>();
        userInfoList = DBHelper.getFriendlist();

        //初始化红包上下文
        applicationContext = this;
        LMMoney.getInstance().initContext(applicationContext);

        EMChat.getInstance().init(context);
        /**
         * debugMode == true 时为打开，sdk 会在log里输入调试信息
         * @param debugMode
         * 在做代码混淆的时候需要设置成false
         */
        EMChat.getInstance().setDebugMode(true);//在做打包混淆时，要关闭debug模式，避免消耗不必要的资源

        //注册一个监听连接状态的listener
        EMChatManager.getInstance().addConnectionListener(new MyConnectionListener());

        //注册新消息监听
//        msgReceiver = new NewMessageBroadcastReceiver();
//        IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
//        intentFilter.setPriority(3);
//        GlobalApplication.getInstance().registerReceiver(msgReceiver, intentFilter);
        // 注册一个cmd消息的BroadcastReceiver
        IntentFilter cmdIntentFilter = new IntentFilter(EMChatManager.getInstance().getCmdMessageBroadcastAction());
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                LogHelper.i("intent:" + intent.getParcelableExtra("message"));
                newMsgFlag = true;
                //获取cmd message对象
                String msgId = intent.getStringExtra("msgid");
                EMMessage message = intent.getParcelableExtra("message");
                Toast.makeText(getApplicationContext(), message.toString(), Toast.LENGTH_SHORT).show();
                //获取消息body
                CmdMessageBody cmdMsgBody = (CmdMessageBody) message.getBody();
                String aciton = cmdMsgBody.action;//获取自定义action
                if (aciton.equals("10") || aciton.equals("11") || aciton.equals("12") || aciton.equals("13")) {
                    String groupId = message.getStringAttribute("group_uniq_id", "0");
                    String userid = loginModel.getData().getUser_uniq_id();
                    if (aciton.equals("10")) {//10 群禁止发言 11 群可以发言啦 12用户禁止发言 13 用户可以发言啦
                        groupBlockList.add(groupId);
                    } else if (aciton.equals("11")) {
                        for (int i = 0; i < groupBlockList.size(); i++) {
                            if (groupBlockList.get(i).equals(groupId)) {
                                groupBlockList.remove(i);
                            }
                        }
                    } else if (aciton.equals("12")) {
                        privateBlockList.put(groupId, userid);
                    } else if (aciton.equals("13")) {
                        privateBlockList.remove(groupId);
                    }
                } else {
                    CenterMessage centerMessage = new CenterMessage();
                    centerMessage.setContent(message.getStringAttribute("content", ""));
                    centerMessage.setGroup_uniq_id(message.getStringAttribute("group_uniq_id", "0"));
                    centerMessage.setHuanxing_groupid( message.getStringAttribute("huanxing_groupid", "0"));
                    centerMessage.setKeywords( message.getStringAttribute("keywords", ""));
                    centerMessage.setSender(message.getStringAttribute("sender", ""));
                    centerMessage.setType(aciton);
                    centerMessage.setCreatTime(System.currentTimeMillis());
                    boolean flag = DBHelper.addCenterMsg(centerMessage);
                }
            }
        }, cmdIntentFilter);

        EMGroupManager.getInstance().addGroupChangeListener(new MyGroupChangeListener());

        EMChat.getInstance().setAppInited();

    }

    /**
     * cmd消息BroadcastReceiver
     */
    private BroadcastReceiver cmdMessageReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            //获取cmd message对象
            String msgId = intent.getStringExtra("msgid");
            EMMessage message = intent.getParcelableExtra("message");
            //获取消息body
            CmdMessageBody cmdMsgBody = (CmdMessageBody) message.getBody();
            String aciton = cmdMsgBody.action;//获取自定义action
            //获取扩展属性
            try {
                String attr = message.getStringAttribute("a");
            } catch (EaseMobException e) {
                e.printStackTrace();
            }
        }
    };

    private class MyGroupChangeListener implements GroupChangeListener {

        @Override
        public void onInvitationReceived(String groupId, String groupName, String inviter, String reason) {

            //收到加入群聊的邀请

            boolean hasGroup = false;
            for (EMGroup group : EMGroupManager.getInstance().getAllGroups()) {
                if (group.getGroupId().equals(groupId)) {
                    hasGroup = true;
                    break;
                }
            }
            if (!hasGroup)
                return;

            // 被邀请
            EMMessage msg = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
            msg.setChatType(EMMessage.ChatType.GroupChat);
            msg.setFrom(inviter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new TextMessageBody(inviter + "邀请你加入了群聊"));
            // 保存邀请消息
            EMChatManager.getInstance().saveMessage(msg);
            // 提醒新消息
            EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();

        }

        @Override
        public void onInvitationAccpted(String groupId, String inviter,
                                        String reason) {
            //群聊邀请被接受
        }

        @Override
        public void onInvitationDeclined(String groupId, String invitee,
                                         String reason) {
            //群聊邀请被拒绝
        }

        @Override
        public void onUserRemoved(String groupId, String groupName) {
            //当前用户被管理员移除出群聊

        }

        @Override
        public void onGroupDestroy(String groupId, String groupName) {
            //群聊被创建者解散
            // 提示用户群被解散

        }

        @Override
        public void onApplicationReceived(String groupId, String groupName, String applyer, String reason) {
            // 用户申请加入群聊，收到加群申请
        }

        @Override
        public void onApplicationAccept(String groupId, String groupName, String accepter) {
            // 加群申请被同意
            EMMessage msg = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
            msg.setChatType(EMMessage.ChatType.GroupChat);
            msg.setFrom(accepter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new TextMessageBody(accepter + "同意了你的群聊申请"));
            // 保存同意消息
            EMChatManager.getInstance().saveMessage(msg);
            // 提醒新消息
            EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();
        }

        @Override
        public void onApplicationDeclined(String groupId, String groupName, String decliner, String reason) {
            // 加群申请被拒绝
        }

    }
//    /**
//     * 注册群组和联系人监听，由于logout的时候会被sdk清除掉，再次登录的时候需要再注册一下
//     */
//    public void registerGroupAndContactListener(){
//        if(!isGroupAndContactListenerRegisted){
//            //注册群组变动监听
//            EMChatManager.getInstance().groupManager().addGroupChangeListener(new MyGroupChangeListener());
//            //注册联系人变动监听
//            EMChatManager.getInstance().contactManager().setContactListener(new MyContactListener());
//            isGroupAndContactListenerRegisted = true;
//        }
//
//    }





    //实现ConnectionListener接口
    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
            //已连接到服务器
        }

        @Override
        public void onDisconnected(final int error) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (error == EMError.USER_REMOVED) {
                        // 显示帐号已经被移除
                    } else if (error == EMError.CONNECTION_CONFLICT) {
                        // 显示帐号在其他设备登陆
                    } else {
                        if (NetUtils.hasNetwork(getInstance())) {
                            //连接不到聊天服务器
                        } else {
                            //当前网络不可用，请检查网络设置
                        }

                    }
                }
            });
        }
    }

NotifyUtil notifyUtil;
    public class NewMessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 注销广播
            abortBroadcast();
            // 消息id（每条消息都会生成唯一的一个id，目前是SDK生成）
            String msgId = intent.getStringExtra("msgid");
            //发送方
            String username = intent.getStringExtra("from");
            // 收到这个广播的时候，message已经在db和内存里了，可以通过id获取mesage对象
            notifyUtil = new NotifyUtil(context, 1);
            Random random = new Random(System.currentTimeMillis());
            PendingIntent contentIntent = PendingIntent.getActivity(context,
                    random.nextInt(), new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
            String Title1 = "你有一条新消息！";
            notifyUtil.notify_normal_singline(contentIntent, R.mipmap.logo, "", Title1, "", true, true, true);

            EMMessage message = EMChatManager.getInstance().getMessage(msgId);
            EMConversation conversation = EMChatManager.getInstance().getConversation(username);
            // 如果是群聊消息，获取到group id
            LogHelper.i("新消息......" + username+",type:"+message.getChatType());
            if (message.getChatType() == EMMessage.ChatType.GroupChat) {
                username = message.getTo();
                if (GlobalApplication.unReadListGroup.get(username) != null) {
                    int numFri = GlobalApplication.unReadListGroup.get(username);
                    GlobalApplication.unReadListGroup.put(username, numFri++);
                    if (MainActivity.getInstance().tabHost.getCurrentTab() == 1) {
                        MainActivity.getInstance().tabHost.setCurrentTab(1);
                    }
                } else {
                    GlobalApplication.unReadListGroup.put(username, 1);
                }
            }else if (message.getChatType() == EMMessage.ChatType.Chat){
                if (GlobalApplication.unReadListFri.get(username) != null) {
                    int numFri = GlobalApplication.unReadListFri.get(username);
                    GlobalApplication.unReadListFri.put(username, ++numFri);
                    numFri = GlobalApplication.unReadListFri.get(username);
                } else {
                    GlobalApplication.unReadListFri.put(username, 1);
                }
            }
            if (!username.equals(username)) {
                return;
            }
        }
    }



}
